<?php

namespace Lib\View;

use Exception;
use Lib\Renderer\RendererInterface;

class View implements ViewInterface
{   
    protected $template;

    protected $variables;

    protected $renderer;

    public function __construct($template = null, array $variables = null)
    {
        $this->variables = $variables;
        $this->template = $template;
    }

    public function initialize()
    {
        if (!$this->renderer instanceof RendererInterface) {
            throw new Exception('É necessario um RendererInterface setado.');
        }
    }

    public function render()
    {
        $this->initialize();

        $path = $this->template . '.html';  

        $this->loadTemplate($path, $this->variables);
    }

    public function setTemplate($template)
    {
        $this->template = $template;
        return $this;
    }

    public function setLayout(boolean $layout)
    {
        $this->layout = $layout;
        return $this;
    }

    protected function loadTemplate($template, array $variables = null)
    {
        if (count($variables) > 0) {
            echo $this->renderer->render($template, $variables);
        } else {
            echo $this->renderer->render($template);
        }
    }

    public function setRenderer(RendererInterface $render)
    {
        $this->renderer = $render;
        return $this;
    }

    public function getRenderer()
    {
        return $this->renderer;
    }
}

